find_package(ROS COMPONENTS catkin)

function(add_rostest file)
  if(rostest_SOURCE_DIR)
    find_program_required(ROSTEST_EXE rostest 
                          PATHS @PROJECT_SOURCE_DIR@/scripts
                          NO_DEFAULT_PATH)
  else()
    find_program_required(ROSTEST_EXE rostest 
                          PATHS @CMAKE_INSTALL_PREFIX@/bin
                          NO_DEFAULT_PATH)
  endif()

  parse_arguments(_rosunit "WORKING_DIRECTORY" "" ${ARGN})
  # HACK: set ROS_TEST_RESULTS_DIR so that rostest puts results where we
  # expect them to be.
  set(_rtrd_setting "ROS_TEST_RESULTS_DIR=${CATKIN_TEST_RESULTS_DIR}")
  if(_rosunit_WORKING_DIRECTORY)
    set(_chdir_prefix "bash -c \"cd ${_rosunit_WORKING_DIRECTORY} && ${_rtrd_setting} ")
  else()
    set(_chdir_prefix "bash -c \"${_rtrd_setting} ")
  endif()
 set(_chdir_suffix "\"")

  # Check that the file exists, #1621
  set(_file_name _file_name-NOTFOUND)
  if(IS_ABSOLUTE ${file})
    set(_file_name ${file})
  else()
    find_file(_file_name ${file}
              PATHS ${CMAKE_CURRENT_SOURCE_DIR}
              NO_DEFAULT_PATH
              NO_CMAKE_FIND_ROOT_PATH)  # for cross-compilation.  thanks jeremy.
    if(NOT _file_name)
      message(FATAL_ERROR "Can't find rostest file \"${file}\"")
    endif()
  endif()

  string(REPLACE "/" "_" _testname ${file})
  get_filename_component(_output_name ${_testname} NAME_WE)
  set(_output_name "${_output_name}.xml")
  append_test_to_cache(catkin-tests "${_chdir_prefix}${ROSTEST_EXE} --pkgdir=${PROJECT_SOURCE_DIR} --package=${PROJECT_NAME} ${_file_name}${_chdir_suffix}")
  append_test_to_cache(catkin-tests "${CHECK_TEST_RAN_EXE} ${CATKIN_TEST_RESULTS_DIR}/${PROJECT_NAME}/TEST-rostest__${_output_name}")
endfunction()
